import React from 'react';
import util from 'util';
import {Collapse, Row, Col, Form, Input, Button, Checkbox, Tooltip, Icon, Table, Modal, message} from 'antd';
import {Search, Edit, FuncTree} from './components/form';
import sys_dict from "sys_dict";
import {SearchDemo, RightButton, ColsEdit} from 'kpl';
import {menus, appMenus, storeMenus, marketMenus, resultMenus, chartMenus} from 'menu';

const confirm = Modal.confirm;
const FormItem = Form.Item;

class Operation extends React.Component {
    render() {
        return <div>
            {this.props.operation ? this.props.children : false}
        </div>
    }
}
//asdf2
class Role extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            key: Math.random(),
            tabOperation: 'table',
            roleTypeOption: {},
            parentRole: [],
            selectedRowKeys: [],
            isLoading: false,
            tblSource: [],
            totalCount: 0,
            modalVisible: false,
            operateType: "ADD",
            operateData: {},
            modalTitle: "",
            editSelectedRowKeys: [[], [], [], [], [], []],
            ifSystem: ""
        };

        this.searchParams = {
            "rolename": "",
            "descript": "",
            "page": 1,
            "rows": sys_dict.defaultPageSize.toString()
        };
        this.rights = [];
        this.loginname = "";
    }

    //asdf23
    componentDidMount() {
        //2
        /*获取loginname*/
        this.loginname = util.getLocalObj("userInfo").loginname;

        this.rights = util.checkRights(["522", "523", "524"]);

        // [true,true,false]

        console.log("right:", this.rights);
        // 界面初始化1
        this.refresh(this.searchParams);
        // 获取父角色名字
        util.httpRequest({
            type: "POST", url: 'role020201.json', params: {}, success: function (result) {
                console.log("父角色：", result);
                let list = [];
                for (let obj of result.rows) {
                    list.push({itemkey: obj.key, itemval: obj.rolename});
                }
                this.setState({
                    parentRole: list
                });
            }.bind(this)
        });
    }

    search(params) {
        console.log(params);
        params.page = "1";
        params.rows = sys_dict.defaultPageSize.toString();
        this.setState({
            searchParams: params
        });
        // 打开等待框
        this.refresh(params);
    }

    refresh(paramdic) {
        this.setState({isLoading: true});
        // 刷新列表数据
        util.httpRequest({
            type: "POST", url: 'role020201.json', params: paramdic, success: function (result) {
                this.setState({
                    isLoading: false,
                    totalCount: result.total,
                    tblSource: result.rows
                });
            }.bind(this)
        });
    }

    config() {
        return {
            search: {
                query: this.query.bind(this)
            }
        }
    }

    show() {
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            operateData: {},
            modalTitle: "新增"
        }, function () {
            var form = this.refs.form.getForm();
            form.resetFields();
        });
    }

    edit(record, index) {
        //ewrs
        //console.log("form",this.props.form);
        this.setState({
            operateData: record,
            modalVisible: true,
            operateType: 'EDIT',
            modalTitle: "修改"
        }, function () {
            var {setFieldsValue} = this.refs.form.getForm();
            setFieldsValue(record);
        });
    }

    onCancel() {
        this.setState({
            visible: false
        });
    }

    onSave() {
        var form = this.refs.form.getForm();
        form.validateFields((errors, values) => {
            if (!!errors) {
                return;
            }
            console.log(values);
            // 关闭弹出框
            this.setState({
                modalVisible: false
            });

            if (this.state.operateType == "EDIT") {
                this.update(this.state.operateData.roleid, values);
            }
            else {
                this.create(values);
            }
        });
    }

    onOk(record, index) {
        // 先删除
        var list = this.state.listdata;
        list.splice(index, 1);
        util.httpRequest({
            type: "POST",
            url: 'role020205.json',
            params: {"roleid": record.roleid, "status": record.status, "loginname": this.loginname},
            success: function (result) {
                this.setState({listdata: list});
            }.bind(this)
        });
    }

    delete(record, index) {
        confirm({
            title: '您是否确认要删除该角色',
            content: "",
            onOk: function () {
                util.httpRequest({
                    type: "POST",
                    url: 'role020205.json',
                    params: {"roleid": record.roleid, "status": record.status, "loginname": this.loginname},
                    success: function (result) {
                        this.refresh(this.searchParams);
                    }.bind(this)
                });
            }.bind(this)
        });
    }

    create(searchValues) {
        searchValues.loginname = this.loginname;
        // 调用新增接口
        util.httpRequest({
            type: "POST", url: 'role020202.json', params: searchValues, success: function (result) {
                this.setState({
                    visible: false
                });
                var params = this.state.searchParams;
                this.refresh(params);
            }.bind(this)
        });
    }

    update(id, values) {
        values.roleid = id;

        values.loginname = this.loginname;
        // 修改角色信息
        util.httpRequest({
            type: "POST", url: 'role020203.json', params: values, success: function (result) {
                this.setState({
                    visible: false
                });
                var params = this.state.searchParams;
                this.refresh(params);
            }.bind(this)
        });
    }

    handleCancel() {
        this.setState({
            modalVisible: false,
        });
    }

    setting(record, index) {
        util.httpRequest({
            type: "POST", url: 'role020206.json', params: {"roleid": record.roleid}, success: function (result) {
                var ids = result.node_ids.split(',');
                //把id按树分组menus, appMenus, storeMenus, marketMenus
                let editSelectedRowKeys = [[], [], [], [],[],[]];
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < menus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[0].push(menus[j].id);
                        } else if (ids[i] == menus[j].id) {
                            editSelectedRowKeys[0].push(ids[i]);
                        }
                        for (let k = 0; k < menus[j].children.length; k++) {
                            if (ids[0] == "SYSTEM") {
                                editSelectedRowKeys[0].push(menus[j].children[k].id);
                            } else if (ids[i] == menus[j].children[k].id) {
                                editSelectedRowKeys[0].push(ids[i]);
                            }
                        }
                    }
                }
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < appMenus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[1].push(appMenus[j].id);
                        } else if (ids[i] == appMenus[j].id) {

                            editSelectedRowKeys[1].push(ids[i]);
                        }
                        for (let k = 0; k < appMenus[j].children.length; k++) {
                            if (ids[0] == "SYSTEM") {
                                editSelectedRowKeys[1].push(appMenus[j].children[k].id);
                            } else if (ids[i] == appMenus[j].children[k].id) {
                                editSelectedRowKeys[1].push(ids[i]);
                            }
                            for (let l = 0; l < appMenus[j].children[k].children.length; l++) {
                                if (ids[0] == "SYSTEM") {
                                    editSelectedRowKeys[1].push(appMenus[j].children[k].children[l].id);
                                } else if (ids[i] == appMenus[j].children[k].children[l].id) {
                                    editSelectedRowKeys[1].push(ids[i]);
                                }
                            }
                        }
                    }

                }
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < storeMenus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[3].push(storeMenus[j].id);
                        } else if (ids[i] == storeMenus[j].id) {
                            editSelectedRowKeys[3].push(ids[i]);
                        }
                        for (let k = 0; k < storeMenus[j].children.length; k++) {
                            if (ids[0] == "SYSTEM") {
                                editSelectedRowKeys[3].push(storeMenus[j].children[k].id);
                            } else if (ids[i] == storeMenus[j].children[k].id) {
                                editSelectedRowKeys[3].push(ids[i]);
                            }
                        }
                    }
                }
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < marketMenus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[2].push(marketMenus[j].id);
                        } else if (ids[i] == marketMenus[j].id) {
                            editSelectedRowKeys[2].push(ids[i]);
                        }
                        for (let k = 0; k < marketMenus[j].children.length; k++) {
                            if (ids[0] == "SYSTEM") {
                                editSelectedRowKeys[2].push(marketMenus[j].children[k].id);
                            } else if (ids[i] == marketMenus[j].children[k].id) {
                                editSelectedRowKeys[2].push(ids[i]);
                            }
                        }
                    }
                }
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < resultMenus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[4].push(resultMenus[j].id);
                        } else if (ids[i] == resultMenus[j].id) {
                            editSelectedRowKeys[4].push(ids[i]);
                        }
                        for (let k = 0; k < resultMenus[j].children.length; k++) {
                            if (ids[0] == "SYSTEM") {
                                editSelectedRowKeys[4].push(resultMenus[j].children[k].id);
                            } else if (ids[i] == resultMenus[j].children[k].id) {
                                editSelectedRowKeys[4].push(ids[i]);
                            }
                        }
                    }
                }
                for (let i = 0; i < ids.length; i++) {
                    for (let j = 0; j < chartMenus.length; j++) {
                        if (ids[0] == "SYSTEM") {
                            editSelectedRowKeys[5].push(chartMenus[j].id);
                        } else if (ids[i] == chartMenus[j].id) {
                            editSelectedRowKeys[5].push(ids[i]);
                        }
                    }
                }
                console.log(editSelectedRowKeys);
                // 如果所修改角色是超级管理员，则勾选所有权限
                if (ids[0] == "SYSTEM") {
                    var systemRoles = editSelectedRowKeys[0].join() + "," + editSelectedRowKeys[1].join() + "," + editSelectedRowKeys[2].join() + "," + editSelectedRowKeys[3].join()+ "," + editSelectedRowKeys[4].join()+ "," + editSelectedRowKeys[5].join();
                    console.log(systemRoles);
                }
                var params = this.state.searchParams;
                this.setState({
                    tabOperation: 'setting',
                    operateData: record,
                    selectedRowKeys: ids[0] == "SYSTEM" ? systemRoles : ids,
                    editSelectedRowKeys: editSelectedRowKeys,
                    ifSystem: ids[0] == "SYSTEM" ? "SYSTEM" : "",
                });
            }.bind(this)
        });
    }

    saveSet() {
        var obj = {};
        obj.roleid = this.state.operateData.roleid;
        console.log(this.state.selectedRowKeys);
        obj.node_ids = this.state.selectedRowKeys.join();
        obj.loginname = this.loginname;
        util.httpRequest({
            type: "POST", url: 'role020209.json', params: obj, success: function (result) {
                console.log("修改权限1：", result);
                this.setState({
                    tabOperation: 'table'
                });
            }.bind(this)
        });
    }

    tableOnChange(selectedRowKeys) {
        this.setState({
            selectedRowKeys: selectedRowKeys
        });
    }

    //dsad2
    treeOnCheck(info) {
        this.changeSelect(info, 0);
    }

    treeOnCheckApp(info) {
        this.changeSelect(info, 1);
    }

    treeOnCheckMarket(info) {
        this.changeSelect(info, 2);
    }

    treeOnCheckProduct(info) {
        this.changeSelect(info, 3);
    }

    treeOnCheckResult(info) {
        this.changeSelect(info, 4);
    }

    treeOnCheckChart(info) {
        this.changeSelect(info, 5);
    }

    changeSelect(info, index) {
        console.log(info);


        
        let editSelectedRowKeys = this.state.editSelectedRowKeys;
        switch (index) {
            case 0:
                editSelectedRowKeys[0] = info;
                break;
            case 1:
                editSelectedRowKeys[1] = info;
                break;
            case 2:
                editSelectedRowKeys[2] = info;
                break;
            case 3:
                editSelectedRowKeys[3] = info;
                break;
            case 4:
                editSelectedRowKeys[4] = info;
                break;
            case 5:
                editSelectedRowKeys[5] = info;
                break;
        }
        this.setState({
            selectedRowKeys: editSelectedRowKeys[0].concat(editSelectedRowKeys[1], editSelectedRowKeys[2], editSelectedRowKeys[3],editSelectedRowKeys[4],editSelectedRowKeys[5]),
            editSelectedRowKeys: editSelectedRowKeys
        });
    }

    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        let params = this.searchParams;
        params.rows = pageSize;
        params.page = current;
        this.refresh(params);
    }

    onChange(page) {
        console.log(page);
        let params = this.searchParams;
        params.page = page;
        this.refresh(params);
    }

    gobackpage() {
        this.setState({
            tabOperation: 'table'
        });
    }

    render() {
        const columnsitem = [{
            title: '角色名称',
            dataIndex: 'rolename',
            key: 'rolename',
        }, {
            title: '描述',
            dataIndex: 'descript',
            key: 'descript',
        }, {
            title: '用户操作',
            key: 'operation',
            render: (text, record, index) => (
                record.rolename != "超级管理员" ?
                    <span>
                    {this.rights[0] ?
                        <a className="a-operate" onClick={this.edit.bind(this, record, index)}>修改</a> : null}
                        {this.rights[0] ? <span className="ant-divider"></span> : null}
                        {this.rights[1] ?
                            <a className="a-operate" onClick={this.setting.bind(this, record, index)}>权限设置</a> : null}
                        {this.rights[1] ? <span className="ant-divider"></span> : null}
                        {this.rights[2] ?
                            <a className="a-operate" onClick={this.delete.bind(this, record, index)}>删除</a> : null}
                </span> : null
            ),
        }];

        const pagination = {
            total: this.state.totalCount,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
            onShowSizeChange: this.onShowSizeChange.bind(this),
            onChange: this.onChange.bind(this)
        };

        const searchConfig = {
            searchTitle: "查询角色信息",
            searchInit: {issuer_code: "", issuer_name: "", card_name: "", bin_num: ""},
            searchBtnType: true,
            searchField: [
                [
                    {propsname: "角色名称", propsKey: "rolename", propsType: "input", key: "111"},
                    {propsname: "描述", propsKey: "descript", propsType: "input", key: "222"},
                    {propsname: "", propsKey: "", propsType: "searchBtn", key: "1234"}
                ]
            ]
        };
        const createConfig = {
            operateTitle: "新增",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {parentroleid: "", rolename: "", descript: ""},
            operateColSm: 24,
            operateCol: {labelCol: 6, wrapperCol: 18},
            operateField: [

                [
                    {
                        propsname: "角色名称", propsKey: "rolename", propsType: "input", key: "111",
                        rules: [{required: true, min: 0, message: '请输入'}]
                    }
                ],
                [
                    {
                        propsname: "描述：",
                        propsKey: "descript",
                        propsType: "input",
                        key: "334",
                        optionData: null
                        ,
                        rules: []
                    }
                ]
            ]
        };

        return (
            <div>
                <Operation operation={this.state.tabOperation == "table"}>
                    <SearchDemo search={this.search.bind(this)} searchConfig={searchConfig}></SearchDemo>
                    <RightButton propsKey="521" btnTxt="+  新增" styleName="addBtn"
                                 oprate={this.show.bind(this)}> </RightButton>
                    <Table pagination={pagination} loading={this.state.isLoading} columns={columnsitem}
                           dataSource={this.state.tblSource} delete={this.delete.bind(this)}/>
                    <Modal visible={this.state.modalVisible} title={this.state.modalTitle} closable={false}
                           footer={[
                               <Button key="back" type="ghost" size="large"
                                       onClick={this.handleCancel.bind(this)}>取消</Button>,
                               <Button key="submit" type="primary" size="large"
                                       onClick={this.onSave.bind(this)}>保存</Button>
                           ]}>
                        <ColsEdit ref="form" key="create" config={createConfig}></ColsEdit>
                    </Modal>
                </Operation>
                <Operation operation={this.state.tabOperation == "setting"}>
                    <Form inline className="ant-advanced-search-form">
                        <Button className="btnMarginRright"
                                onClick={this.gobackpage.bind(this)}>返回</Button>
                        {this.state.ifSystem != "SYSTEM" ?
                            < Button className="btnMarginRright" type="primary" htmlType="submit"
                                     onClick={this.saveSet.bind(this)}>保存</Button> : ""}
                        < FormItem label="角色ID：">
                            {this.state.operateData.roleid}
                        </FormItem>
                        <FormItem label="角色名称：">
                            {this.state.operateData.rolename}
                        </FormItem>
                        <FormItem label="描述：">
                            {this.state.operateData.descript}
                        </FormItem>
                    </Form>
                    <Row>
                        <Col span={6}>
                            <div>系统管理</div>
                            <FuncTree treeOnCheck={this.treeOnCheck.bind(this)} menudata={menus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                        <Col span={6}>
                            <div>业务管理</div>
                            <FuncTree treeOnCheck={this.treeOnCheckApp.bind(this)} menudata={appMenus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                        <Col span={6}>
                            <div>营销管理</div>
                            <FuncTree treeOnCheck={this.treeOnCheckMarket.bind(this)} menudata={marketMenus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                        <Col span={6}>
                            <div>商户商品管理</div>
                            <FuncTree treeOnCheck={this.treeOnCheckProduct.bind(this)} menudata={storeMenus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <div>业务查询</div>
                            <FuncTree treeOnCheck={this.treeOnCheckResult.bind(this)} menudata={resultMenus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                        <Col span={6}>
                            <div>统计分析</div>
                            <FuncTree treeOnCheck={this.treeOnCheckChart.bind(this)} menudata={chartMenus}
                                      selecteds={this.state.selectedRowKeys}>
                            </FuncTree>
                        </Col>
                    </Row>
                </Operation>
            </div>
        );
    }
}

export default Role;